package com.fg.tliaswebmanagement.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.fg.tliaswebmanagement.common.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url
        String url = request.getRequestURL().toString();
        log.info("请求的URL：{}",url);

        if (url.contains("/login")) {
            log.info("登录操作");
            filterChain.doFilter(request, response);
            return;
        }

        //获取token
        String jwt = request.getHeader("Authorization");
        if (StrUtil.isEmpty(jwt)) {
            log.info("请求token为空");
            Result result = Result.error("token不能为空");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(result));
            return;
        }

        //解析token
        try {
            JWTPayload s = JWTUtil.parseToken(jwt).getPayload();
            JSONUtil.parseObj(s);
            log.info("token数据：{}", s);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token失效");
            Result result = Result.error("token失效");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(result));
            return;
        }
        filterChain.doFilter(request, response);
    }
}
